package cn.jsl.basic.controller;

import cn.jsl.basic.util.AjaxResult;
import cn.jsl.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //文件上传接口
    @PostMapping
    //element-ui提供的文件上传框默认的name="file"
    private AjaxResult upload(@RequestPart MultipartFile file){
        try {
            //获取文件的全部路径
            String originalFilename = file.getOriginalFilename();
            //获取文件的后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String upload = FastDfsUtil.upload(file.getBytes(), substring);
            //将文件响应给前端
            return AjaxResult.me().setResultObj(upload);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败,请稍后重试!");
        }
    }
    //文件上传第二种方式(简便一点的方式)
//    @PostMapping
//    public AjaxResult upload(@RequestPart(value = "file", required = true) MultipartFile file){
//        try {
//            String filename = file.getOriginalFilename();
//            String extName = filename.substring(filename.lastIndexOf(".")+1);
//            String resultPath = FastdfsUtil.upload(file.getBytes(), extName);
//            return AjaxResult.me().setResultObj(resultPath);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后重试！！！！");
//        }
//    }

    //文件删除接口
    @DeleteMapping//http://47.95.117.210:8888/fastDfs?path=rBE3kWJBnwCAehKXAAQ3ZQryGmo596.jpg
    private AjaxResult delete(@RequestParam(value = "path",required = true) String path){
        try {
            //获取第一个斜杠后面的内容 /group1/M00/03/57/rBE3kWJBnwCAehKXAAQ3ZQryGmo596.jpg
            String substring = path.substring(1);
            //获取从零开始到第一个斜杠(group1)  group1/M00/03/57/rBE3kWJBnwCAehKXAAQ3ZQryGmo596.jpg
            String substring1 = substring.substring(0, substring.indexOf("/"));
            //    M00/03/57/rBE3kWJBnwCAehKXAAQ3ZQryGmo596.jpg
            String substring2 = substring.substring(substring.indexOf("/") + 1);
            FastDfsUtil.delete(substring1, substring2);
            //返回前端
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件删除失败,请稍后重试!");
        }

    }
}
